package com.ysw.rpc.client.handler.inbound;

import com.ysw.rpc.client.config.ClientProperties;
import com.ysw.rpc.client.enums.ConnectionEnum;
import com.ysw.rpc.client.utils.PromiseUtil;
import com.ysw.rpc.common.messages.Response;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;

/**
 * 响应处理器
 *
 * @author YinShangwen
 * @since 2023/4/4 14:08
 */
@ChannelHandler.Sharable
public class ResponseHandler extends SimpleChannelInboundHandler<Response> {
    private final ClientProperties properties;

    public ResponseHandler(ClientProperties properties) {
        this.properties = properties;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Response msg) {
        Promise<Response> promise = PromiseUtil.get(msg.getRequestId());
        promise.setSuccess(msg);
        if (ConnectionEnum.isShort(properties.getConnectionType())) {
            ctx.channel().close();
        }
    }
}
